﻿using System;
using ShureValidation.Language;

namespace ShureValidation.Rules
{
    /// <summary>
    /// Checks if a primitive type is between min and max.
    /// </summary>
    /// <para>
    /// Language file items:
    /// <list type="table">
    ///     <listheader>
    ///         <term>ItemName</term>
    ///         <description>Language text</description>
    ///     </listheader>
    ///     <item>
    ///         <term>Between</term>
    ///         <description>'{0}' must be between {1} and {2}.</description>
    ///     </item>
    ///     <item>
    ///         <term>BetweenString</term>
    ///         <description>'{0}' may only have {1} up to {2} letters.</description>
    ///     </item>
    ///	  <item>
    ///		  <term>BetweenStringLength</term>
    ///          <description>'{0}' must be {1} letters long.</description>
    ///      </item>
    /// </list>
    /// </para>
    [LanguagePrompt("Between", "'{0}' must be between {1} and {2}.")]
    [LanguagePrompt("BetweenString", "'{0}' may only have {1} up to {2} characters.")]
    [Serializable]
    public class BetweenRule : IRule
    {
        private readonly object _max;
        private readonly object _min;
        private object _value;

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidateAttribute"/> class.
        /// </summary>
        /// <param name="min">Value must be equal to this or larger.</param>
        /// <param name="max">Value must be equal or less than this.</param>
        /// <exception cref="ArgumentException">Thrown if the max value is more than the min value</exception>
        public BetweenRule(object min, object max)
        {
            var comparable = (IComparable) min;
            if (comparable.CompareTo(max) > 0)
                throw new ArgumentException("max cannot be less than min.");
            _min = min;
            _max = max;
        }


        /// <summary>
        /// Max value
        /// </summary>
        public object Max
        {
            get { return _max; }
        }

        /// <summary>
        /// Min value
        /// </summary>
        public object Min
        {
            get { return _min; }
        }

        #region IRule Members

        /// <summary>
        /// Validate a field value
        /// </summary>
        /// <param name="value">Value to validate</param>
        /// <returns><c>true</c> if validation was successful; otherwise <c>false</c>.</returns>
        /// <exception cref="NotSupportedException">Value type is not supported by this rule.</exception>
        public bool Validate(object value)
        {
            if (ValueChecker.IsEmpty(value))
                return true;

            _value = value;
            if (value is string)
            {
                var s = (string) value;
                return s.Length >= (int) Min && s.Length <= (int) Max;
            }

            var comparable = value as IComparable;
            if (comparable != null)
                return comparable.CompareTo(Max) <= 0 && comparable.CompareTo(Min) >= 0;


            throw new NotSupportedException(GetType() + " do not support " + value.GetType());
        }

        /// <summary>
        /// Format an error message
        /// </summary>
        /// <param name="fieldName">Field (have already been translated)</param>
        /// <param name="rulesLanguage">Language prompts for validation rules</param>
        /// <returns>Error message formatted for the current language.</returns>
        public string Format(string fieldName, IModelLanguage rulesLanguage)
        {
            if (_value is string)
                return string.Format(rulesLanguage[_min.Equals(_max) ? "BetweenStringLength" : "BetweenString"],
                                     fieldName, _min, _max);

            return string.Format(rulesLanguage["Between"], fieldName, _min, _max);
        }

        /// <summary>
        /// Checks if this rule support values of the specified format.
        /// </summary>
        /// <param name="type">Type of value</param>
        /// <returns><c>true</c> if the specified type can be validated; otherwise <c>false</c>.</returns>
        public bool SupportsType(Type type)
        {
            return typeof(IComparable).IsAssignableFrom(type);
        }

        #endregion
    }
}